package com.nervenets.web.controller.order;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ShopCartItem implements Serializable {
    private long productId;
    private String logo;
    private String name;
    private int price;
    private int total;
    private HashMap<Long, Integer> timeCardFree = new HashMap<>();//免费关联时间卡及免费件数

    public boolean setFree(long timeCardId, int free) {
        if (!this.timeCardFree.containsKey(timeCardId)) {
            this.timeCardFree.put(timeCardId, free);
            return true;
        }
        return false;
    }

    public int canFreeTotal() {
        return total - getFree();
    }

    public boolean canFree() {
        return getFree() < total;
    }

    public int getFree() {
        AtomicInteger free = new AtomicInteger();
        this.timeCardFree.forEach((aLong, integer) -> free.addAndGet(integer));
        return free.intValue();
    }

    public void clearFree() {
        this.timeCardFree.clear();
    }

    public int getPayMoney() {
        return this.price * (this.total - this.getFree());
    }

    public ShopCartItem(long productId) {
        this.productId = productId;
    }

    public ShopCartItem(long productId, String logo, String name, int price, int total) {
        this.productId = productId;
        this.logo = logo;
        this.name = name;
        this.price = price;
        this.total = total;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof ShopCartItem)) return false;
        ShopCartItem that = (ShopCartItem) o;
        return getProductId() == that.getProductId();
    }

    @Override
    public int hashCode() {

        return Objects.hash(getProductId());
    }
}
